import 'package:flutter/material.dart';
import 'package:ideology/shared/services/explorer_persistence.dart';
import 'package:ideology/shared/widgets/file_explorer/file_explorer_controller.dart';

/// 资源管理器状态管理器
///
/// 负责：
/// - 恢复/保存项目的资源管理器展开状态、选中项与滚动位置
/// - 清理指定项目的持久化状态并重置 UI
class ExplorerStateManager {
  /// 创建 [ExplorerStateManager]
  ///
  /// - [explorerController] 文件资源管理器控制器
  /// - [explorerScrollController] 滚动控制器
  /// - [scopeFor] 作用域生成函数（基于项目路径）
  ExplorerStateManager({
    required this.explorerController,
    required this.explorerScrollController,
    required String Function(String) scopeFor,
  }) : _scopeFor = scopeFor;

  /// 文件资源管理器控制器
  final FileExplorerController explorerController;

  /// 资源管理器滚动控制器
  final ScrollController explorerScrollController;

  /// 根据目录路径生成唯一作用域的函数
  final String Function(String) _scopeFor;

  /// 恢复某项目的资源管理器状态
  ///
  /// - 包括展开的节点、选中的路径和滚动位置
  /// - 若没有持久化记录，则不做处理
  Future<void> restoreForProject(String dirPath) async {
    final persistence = ExplorerPersistence(_scopeFor(dirPath));
    final persisted = await persistence.load();
    if (persisted == null) return;

    explorerController.applyFromMap({
      'expanded': persisted.expanded.toList(),
      'selectedPath': persisted.selectedPath,
    });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!explorerScrollController.hasClients) return;
      final max = explorerScrollController.position.maxScrollExtent;
      final target = persisted.scrollOffset.clamp(0.0, max);
      explorerScrollController.jumpTo(target);
    });
  }

  /// 保存某项目的资源管理器状态
  ///
  /// 会将当前展开的节点、选中的路径和滚动位置持久化
  Future<void> saveForProject(String dirPath) async {
    final persistence = ExplorerPersistence(_scopeFor(dirPath));
    final state = ExplorerPersistedState(
      expanded: {...explorerController.expanded.value},
      selectedPath: explorerController.selectedPath.value,
      scrollOffset: explorerScrollController.hasClients
          ? explorerScrollController.offset
          : 0.0,
    );
    await persistence.save(state);
  }

  /// 清理某项目的持久化状态并把当前 UI 重置为初始
  ///
  /// - 删除持久化数据
  /// - 重置展开/选中状态
  /// - 清空子节点缓存
  /// - 滚动位置归零
  Future<void> clearForProject(String dirPath) async {
    final persistence = ExplorerPersistence(_scopeFor(dirPath));
    await persistence.clear();

    // 清空控制器状态 + 滚动位置（恢复到初始空白页）
    explorerController.expanded.value = {};
    explorerController.select(null);
    explorerController.loadedChildren.clear();
    explorerController.childrenRevision.value++; // 强制刷新
    if (explorerScrollController.hasClients) {
      try {
        explorerScrollController.jumpTo(0);
      } catch (_) {}
    }
  }
}
